package org.example.kidscode.controller;

import org.example.kidscode.entity.Student;
import org.example.kidscode.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/api/students")
public class StudentController {

    @Autowired
    private StudentService studentService;

    // ✅ 查询所有学生
    @GetMapping
    public List<Student> getAllStudents() {
        return studentService.findAll();
    }

    // ✅ 根据ID查询学生
    @GetMapping("/{id}")
    public ResponseEntity<Student> getStudentById(@PathVariable("id") String id) {
        return studentService.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    // ✅ 新增或更新学生
    @PostMapping
    public Student createOrUpdateStudent(@RequestBody Student student) {
        return studentService.save(student);
    }

    // ✅ 删除学生
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteStudent(@PathVariable("id") String id) {
        if (studentService.findById(id).isPresent()) {
            studentService.deleteById(id);
            return ResponseEntity.noContent().build();
        }
        return ResponseEntity.notFound().build();
    }

    // ✅ 批量导入学生（上传 Excel 文件）
    @PostMapping("/upload")
    public ResponseEntity<String> uploadStudents(@RequestParam("file") MultipartFile file) {
        try {
            studentService.importStudentsFromExcel(file);
            return ResponseEntity.ok("学员导入成功！");
        } catch (Exception e) {
            e.printStackTrace(); // 打印错误方便调试
            return ResponseEntity.badRequest().body("导入失败：" + e.getMessage());
        }
    }
    @PutMapping("/{id}")
    public ResponseEntity<Student> updateStudent(@PathVariable("id") String id, @RequestBody Student student) {
        // 确保主键一致
        student.setStudentId(id);
        Student updated = studentService.save(student);
        return ResponseEntity.ok(updated);
    }
}
